import { Component, Input, OnInit } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { ApesModalRef } from '@shared/apes/modal';
import { deepClone } from '../../utils/utils';
import { UserAuthService } from '@core/services/user-auth.service';
import { FormGroup } from '@angular/forms';


@Component({
  selector: 'dialog-inquiry',
  templateUrl: './dialog-inquiry.component.html',
})
export class DialogInquiryComponent implements OnInit {
  model: any = {};
  options: any;
  resultsData: any = [];

  body: any = {
    // 'item': [
    //   {
    //     'YSPMC': '原厂点火线圈30520RNAA01',
    //     'item': [
    //       {
    //         'PZID': '001',
    //         'JGYXQ': '15',
    //         'YSPMC': '原厂点火线圈30520RNAA01',
    //         'XSXJ': 150,
    //         'PZMC': '原厂(4S店)件',
    //         'SSBL': 0.17,
    //         'PJMCID': '000613',
    //         'SPMC': '原厂国内(4S店)(广汽)点火线圈CGT08208A',
    //         'supplier': '供应商 884',
    //         'DABJ': 0,
    //         'YSPID': '0000990598',
    //         'SPID': '0002620092',
    //         'YXQZ': 1626278400000,
    //         'GSID': '1001',
    //         'HYZT': 1,
    //         'LYDJLX': 'servicePlan',
    //         'SPXH': '30520RNAA01',
    //         'CPHM': '川WZZZZZ',
    //         'LYDJHM': 'FW10012106123130',
    //         'PLID': 'M01010104001',
    //         'PPMC': '原厂国内(4S店)',
    //         'CJHM': 'LHGCP168298033369',
    //         'HSBL': 1,
    //         'PJMC': '点火线圈',
    //         'PLMC': '点火线圈',
    //         'XFPZID': '00101',
    //         'PTID': '1001',
    //         'PPID': '100002',
    //         'CGZID': '0022',
    //         'PZCXMC': '本田雅阁_第八代雅阁2009年 2.0 自动 EX Navi 标准导航版',
    //         'SPZMC': '一般商品',
    //         'PZCXID': 'CGH0120A00310',
    //         'SPZID': '10',
    //         'SB': 0,
    //         'MDID': 'A001',
    //         'CGZZID': '1001',
    //         'RKDJ': 125,
    //         'CGZZMC': '广州市集群车宝汽车服务连锁有限公司',
    //         'CGZMC': '佛山采购组',
    //         'XJDH': '1101031686',
    //         'GG': '1个',
    //         'GYSMC': '广州市舜达舜汽车配件有限公司(经销)',
    //         'XSDJ': 291,
    //         'ZDMC': '佛山中转站',
    //         'ZDID': '000842',
    //         'GYSID': '00000897',
    //         'XJBLQ': 1632758400000,
    //         'XH': 1,
    //         'CGDJ': 125,
    //         'JLDW': '个',
    //         'YJDHSC': 8,
    //       },
    //       {
    //         'PZID': '000001',
    //         'JGYXQ': '15',
    //         'YSPMC': '原厂点火线圈30520RNAA01',
    //         'XSXJ': 43,
    //         'PZMC': '品牌件',
    //         'SSBL': 0.17,
    //         'PJMCID': '000613',
    //         'SPMC': '湘火炬点火线圈DSFHBBA',
    //         'supplier': '供应商 884',
    //         'DABJ': 0,
    //         'YSPID': '0000990598',
    //         'SPID': '0002620093',
    //         'YXQZ': 1626278400000,
    //         'CGBZ': '434rs',
    //         'GSID': '1001',
    //         'HYZT': 1,
    //         'LYDJLX': 'servicePlan',
    //         'SPXH': '30520RNAA01',
    //         'GYSBZ': 'dfdsfsdf',
    //         'CPHM': '川WZZZZZ',
    //         'LYDJHM': 'FW10012106123130',
    //         'PLID': 'M01010104001',
    //         'PPMC': '湘火炬',
    //         'CJHM': 'LHGCP168298033369',
    //         'HSBL': 1,
    //         'PJMC': '点火线圈',
    //         'PLMC': '点火线圈',
    //         'PTID': '1001',
    //         'PPID': '002611',
    //         'CGZID': '0022',
    //         'PZCXMC': '本田雅阁_第八代雅阁2009年 2.0 自动 EX Navi 标准导航版',
    //         'SPZMC': '一般商品',
    //         'PZCXID': 'CGH0120A00310',
    //         'SPZID': '10',
    //         'SB': 0,
    //         'MDID': 'A001',
    //         'CGZZID': '1001',
    //         'RKDJ': 36,
    //         'CGZZMC': '广州市集群车宝汽车服务连锁有限公司',
    //         'CGZMC': '佛山采购组',
    //         'XJDH': '1101031686',
    //         'GG': '1个',
    //         'GYSMC': '广州市舜达舜汽车配件有限公司(经销)',
    //         'XSDJ': 90,
    //         'ZDMC': '佛山中转站',
    //         'ZDID': '000842',
    //         'GYSID': '00000897',
    //         'XJBLQ': 1632758400000,
    //         'XH': 2,
    //         'CGDJ': 36,
    //         'JLDW': '个',
    //         'YJDHSC': 8,
    //       },
    //     ],
    //     'name': '原厂点火线圈30520RNAA01',
    //     'id': '0000990598',
    //     'YSPID': '0000990598',
    //   },
    // ],
    // 'PZCXMC': '本田雅阁_第八代雅阁2009年 2.0 自动 EX Navi 标准导航版',
    // 'CPHM': '川WZZZZZ',
    // 'PZCXID': 'CGH0120A00310',
  };

  @Input() conditionModel: any;
  @Input() gridData: any;

  id: string;                               // 方案号

  isLoading: boolean = false;
  tabSetIndex: any = 0;
  inquiryInitData: any = {};
  inquiryLeftData: any[] = [];
  inquiryRightData: any[] = [];
  inquiryShowData: any[] = [];
  postTotal: any = 0;

  inquiryTotal: any = 0;
  quoted: any = 0;
  showHidden: boolean = false;
  multiple: boolean = true;

  filterField: any = [
    { type: 'PJMC', name: '配件' }, // 配件
    { type: 'ZDMC', name: '送达站点' }, // 送达站点
    { type: 'PZMC', name: '品质' }, // 品质
    { type: 'supplier', name: '供应商代码' }, // 供应商
  ];


  // logisticsModeForm = new FormGroup({});
  logisticsModeForm: FormGroup;
  logisticsModeFields: any[] = [{
    key: 'logisticsMode',
    templateOptions: {
      api: 'fn.servicePlanceService.queryCarrierFrom',
      init: true,
      items: [],
      placeholder: '配送方式',
      hideLabel: 'true',
      divCol: 24,
      lblCol: 0,
      input: 24,
      disabled: 'model.selectFlag == 0',
      valueFormatter: '"["+ value.id + "]" + value.name',
      downFormatter: '"["+ value.id + "]" + value.name',
      domain: '{"filters":[{"field":"EXTERNAL_GYSID","operator":"EQ","value":"model.EXTERNAL_GYSID"},{"field":"MDID","operator":"EQ","value":"model.MDID"}],"groups":[],"operator":"and"}',
    },
    onDepends: '[{"method":"debugger;","field":"logisticsMode","fields":["logisticsMode"],"isTable":false}]',
    type: 'select',
  }];


  constructor(private apiService: ApiService,
              protected userService: UserAuthService,
              private msg: ApesMessageService,
              public modal: ApesModalRef) {

  }

  ngOnInit() {
    this.resetInquiry(true);
  }

  resetInquiry(init) {
    let api = 'commodityInquiry.order.getQuotationRatio';
    let setData = deepClone(this.conditionModel);
    let platform = this.userService.getUserInfoObj() ? this.userService.getUserInfoObj().platform : '';
    const data = { ...setData, platform: platform };
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          if (body) {
            this.inquiryTotal = body.inquiryTotal;
            this.quoted = body.Quoted;
          }
        }
      });
    this.getInquiryData(data, init);
  }

  getInquiryData(data, init) {
    let api = 'commodityInquiry.order.getInquiryPool';
    this.isLoading = true;
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.inquiryInitData = body;
          this.inquiryLeftData = body.item;
          this.postTotal = 0;
          this.inquiryRightData = this.filtrationSelect(body.item, init);
          this.inquiryShowData = deepClone(this.inquiryRightData);
          this.filterCondition(init);
          if (this.conditionModel.hasOwnProperty('node')) {
            this.checkFiltrationData();
          }
        }
        this.isLoading = false;
        this.onSelectionChanged(this.inquiryRightData);
        // console.log('返回数据', this.inquiryInitData);
      });
  }

  filtrationSelect(params, init) {
    let param = deepClone(params);
    param.forEach((com) => {
      com.item.forEach((list) => {
        let selectFlag = 0;
        if (list.hasOwnProperty('WYZ')) {
          let gridData;
          if (init) {
            gridData = deepClone(this.gridData);
          } else {
            gridData = deepClone(this.inquiryRightData);
          }
          gridData.forEach((data) => {
            if (init) {
              if (data.hasOwnProperty('uniqueValue') && data['uniqueValue'] == list['WYZ']) {
                selectFlag = 1;
                list['refactorData'] = deepClone(data);
                if (list['refactorData'].hasOwnProperty('logisticsMode')) {
                  list['logisticsMode'] = list['refactorData']['logisticsMode'];
                }
              }
            } else {
              data.item.forEach((res) => {
                if (res.hasOwnProperty('WYZ') && res['WYZ'] == list['WYZ']) {
                  selectFlag = res.selectFlag;
                  list['refactorData'] = deepClone(res['refactorData']);
                  if (list['refactorData'] && list['refactorData'].hasOwnProperty('logisticsMode')) {
                    list['logisticsMode'] = list['refactorData']['logisticsMode'];
                  }
                }
              });
            }
          });
        } else {
          selectFlag = 0;
        }
        list.selectFlag = selectFlag;
        // if (!list['logisticsModeFields']) {
        //   if (!list.hasOwnProperty('EXTERNAL_GYSID')) {
        //     list['EXTERNAL_GYSID'] = null;
        //   }
        //   list['logisticsModeFields'] = [{
        //     key: 'logisticsMode',
        //     templateOptions: {
        //       api: 'fn.servicePlanceService.queryCarrierFrom',
        //       init: true,
        //       items: [],
        //       placeholder: '配送方式',
        //       hideLabel: 'true',
        //       divCol: 24,
        //       lblCol: 0,
        //       input: 24,
        //       valueFormatter: '"["+ value.id + "]" + value.name',
        //       downFormatter: '"["+ value.id + "]" + value.name',
        //       domain: '{"filters":[{"field":"EXTERNAL_GYSID","operator":"EQ","value":"{{model.EXTERNAL_GYSID}}"},{"field":"MDID","operator":"EQ","value":"{{model.MDID}}"}],"groups":[],"operator":"and"}',
        //     },
        //     onDepends: '[{"method":"debugger;","field":"logisticsMode","fields":["logisticsMode"],"isTable":false}]',
        //     type: 'select',
        //     expressionProperties: {'templateOptions.disabled': " model.selectFlag != 0 "}
        //   }];
        // }

        if (!list['logisticsModeItems']) {
          list['logisticsLoading'] = false;
          if (list['logisticsMode']) {
            list['logisticsModeItems'] = [...list['logisticsMode']];
          } else {
            list['logisticsModeItems'] = [];
          }
        }
      });
    });
    return param;
  }

  logisticsModeChange(e, param) {
    console.log(param);
  }

  checkLogisticsMode(param) {
    let item = param['logisticsModeItems'];
    if (item.length <= 1) {
      param['logisticsLoading'] = true;
      let api = 'fn.servicePlanceService.queryCarrierFrom';
      let setData = {
        'EXTERNAL_GYSID': param['EXTERNAL_GYSID'],
        'MDID': param['MDID'],
      };
      this.apiService.post(api, setData).subscribe((body) => {
        console.log(body);
        param['logisticsLoading'] = false;
        param['logisticsModeItems'] = body;
      });
    }
  }

  filterCondition(init) {

    this.filterField.forEach((field) => {
      field.data = [];
      field.data = this.filtrationData(field.type, init);
    });
  }

  filtrationData(type, init) {
    let showData = [];
    let list = deepClone(this.inquiryLeftData);
    let node = deepClone(this.conditionModel.node);
    list.forEach((data) => {
      data.item.forEach((res) => {
        let check = true;
        showData.forEach((sd) => {
          if (sd[type] == res[type]) {
            check = false;
          }
        });
        if (check) {
          let checked = true;
          if (node && type == 'PJMC' && init) {
            if (res[type] == node['category']['name']) {
              checked = true;
            } else {
              checked = false;
            }
          }
          showData.push({ [type]: res[type], checked: checked });
        }
      });
    });
    return showData;
  }

  checkFiltrationData() {
    // console.log(this.filterField);
    let show = true;
    let list = deepClone(this.inquiryRightData);
    list.forEach((data) => {
      data.item = data.item.filter((item) => {
        return this.filter(item);
      });
      if (data.item.length != 0) {
        show = false;
      }
    });
    this.inquiryShowData = list;
    this.showInquiry = show;
  }

  showInquiry: boolean = false;

  filter(filterData) {
    let check = true;
    this.filterField.forEach((field) => {
      let type = field.type;
      field.data.forEach((data) => {
        if (data[type] == filterData[type] && check != false) {
          check = data.checked;
        }
      });
    });
    return check;
  }

  selectProduct(data, list) {
    if(!data.logisticsMode && data.selectFlag == 0) {
      return this.msg.error('请选择对应物流方式！');
    }
    data.selectFlag = data.selectFlag == 0 ? 1 : 0;

    if (data.selectFlag == 1) {
      list.item.forEach((li) => {
        if (data.WYZ != li.WYZ && data.SPID == li.SPID) {
          li.selectFlag = 0;
        }
      });
    }

    this.inquiryRightData.forEach((res) => {
      if (res.YSPID == list.YSPID) {
        res.item.forEach((re) => {
          if (re.SPID == data.SPID) {
            if (re.WYZ == data.WYZ && data.selectFlag == 1) {
              re.selectFlag = data.selectFlag;
              re['logisticsMode'] = data['logisticsMode'];
              if (!re.hasOwnProperty('refactorData') || re.refactorData == undefined) {
                this.postTotal = this.postTotal + 1;
                this.resultsData = [];
                this.getInquiryPoolItem(re, (reData) => {
                  re['refactorData'] = reData;
                  this.postTotal = this.postTotal - 1;
                  if (this.postTotal == 0) {
                    this.onSelectionChanged(this.inquiryRightData);
                  }
                });
              } else {
                if (re.refactorData.hasOwnProperty('logisticsMode')) {
                  re.refactorData['logisticsMode'] = data['logisticsMode'];
                }
              }
            } else {
              re.selectFlag = 0;
            }
          }
        });
      }
    });

    if (this.postTotal == 0) {
      this.onSelectionChanged(this.inquiryRightData);
    }
  }

  getInquiryPoolItem(data, callBack) {
    let api = 'fn.service.getInquiryPoolItem';
    let setData = { 'PUR_SPXJDMX': [data], ...this.conditionModel };

    this.apiService.post(api, { 'body': JSON.stringify(setData) }).subscribe(
      (body) => {
        // console.log(body);
        if (body) {
          callBack(body[0]);
        }
      });
  }

  onSelectionChanged(selectedRow) {

    const data = [];
    selectedRow.forEach((list) => {
      list.item.forEach((item) => {
        if (item.selectFlag == 1) {
          data.push(item['refactorData']);
        }
      });
    });
    this.resultsData = data;
  }

  destroyModal(): void {
    this.modal.destroy(this.resultsData);
  }

  openShowHidden() {
    this.showHidden = !this.showHidden;
  }

  resetCondition() {
    this.tabSetIndex = 0;
    this.filterField.forEach((field) => {
      field.data.forEach((data) => {
        data.checked = true;
      });
    });
    this.inquiryShowData = deepClone(this.inquiryRightData);
    this.showInquiry = false;
  }

}
